package netty.ProtoBuf.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * @ClassName NettyClient
 * @Description TODO
 * @Author director吴
 * @Date 2022/1/20 12:55
 * @Version 1.0
 **/
public class NettyClient {

    public static void main(String[] args) {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();


        //客户端启动对象
        Bootstrap bootstrap = new Bootstrap();
        try {

        //设置参数
        bootstrap.group(eventExecutors).                            //设置线程组
                channel(NioSocketChannel.class).                    //设置客户端通道对象
                handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //在pipeline 中加入pojoBufHandler
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("encoder", new ProtobufEncoder());
                pipeline.addLast(new ClientHandler());
            }
        });

        System.out.println("客户端准备就绪");


        //启动客户端连接服务
        //---------------ChannelFuture Netty异步模型

            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();

            //监听通道 --  并关闭
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventExecutors.shutdownGracefully();
        }

    }
}
